<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请单号" prop="paymentRequestCode">
        <el-input v-model="queryParams.paymentRequestCode" placeholder="请输入计划单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="采购单号" prop="ordersNumber">
        <el-input v-model="queryParams.ordersNumber" placeholder="请输入计划单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供应商" prop="vendorId">
        <treeselect v-model="queryParams.vendorId" :options="vendorOptions" :show-count="true" placeholder="请输入供应商"
          style="width: 210px" />
      </el-form-item>
      &nbsp;
      <el-form-item label="状态筛选" prop="statusFilter">
        <el-select v-model="queryParams.statusFilter" placeholder="请选择状态" clearable>
          <!-- 付款状态分组 -->
          <el-option-group label="付款状态">
            <el-option v-for="dict in dict.type.request_payment_status" :key="'pay-' + dict.value" :label="dict.label"
              :value="'pay-' + dict.value" />
          </el-option-group>

          <!-- 申请状态分组 -->
          <el-option-group label="申请状态">
            <el-option v-for="dict in dict.type.payment_review_status" :key="'review-' + dict.value" :label="dict.label"
              :value="'review-' + dict.value" />
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="deleteStatus">
        <el-select v-model="queryParams.deleteStatus" placeholder="请选择订单状态" clearable>
          <el-option v-for="dict in dict.type.tb_delete_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-check" size="mini" @click="submitApproved"
          v-hasPermi="['finance:paymentRequest:approved']">批量核准（并生成付款单）</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-finished"
          size="mini"
          :disabled="multiple"
          @click="sumbitVoucher"
          v-hasPermi="['finance:paymentRequest:voucher']"
          >付款（合并生成付款单）</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-close" size="mini" :disabled="multiple" @click="handleReject"
          v-hasPermi="['finance:paymentRequest:reject']">批量驳回</el-button>
      </el-col>
      <span v-if="totalAmount > 0" style="margin-left: 5%;font-size:16px">
        汇总金额：<span style="color:green;font-weight:800">{{ totalAmount.toFixed(2) }}</span>
      </span>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getPaymentRequestList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paymentRequestList" ref="myTable">
      <el-table-column align="center" width="20" type="expand">
        <template slot-scope="scope">
          <el-table :data="scope.row.paymentRequests"
            @selection-change="(val) => handleSelectionChange(val, scope.row.ordersNumber)">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="申请单号" align="center" prop="paymentRequestCode" />
            <el-table-column label="申请状态" align="center" prop="paymentReviewStatus">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.payment_review_status" :value="scope.row.paymentReviewStatus" />
              </template>
            </el-table-column>
            <el-table-column label="付款类型" align="center" prop="paymentType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.request_payment_type" :value="scope.row.paymentType" />
              </template>
            </el-table-column>
            <el-table-column label="申请金额" align="center">
              <template v-slot="scope">
                {{
                  scope.row.payableAmount
                    ? scope.row.payableAmount.toFixed(2)
                    : scope.row.prepaymentAmount.toFixed(2)
                }}
              </template>
            </el-table-column>
            <el-table-column label="付款状态" align="center" prop="paymentStatus">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.request_payment_status" :value="scope.row.paymentStatus" />
              </template>
            </el-table-column>
            <el-table-column label="预付款备注" align="center" prop="prepaymentRemark" />
            <el-table-column label="申请人/申请日期" align="center">
              <template slot-scope="scope">
                {{ scope.row.applicant }}<br />{{
                  scope.row.applicationTime
                }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="[
                  'inance:paymentRequest:reject',
                  'finance:advance:applicant',
                  'product:PaymentRequestProcess:list',
                ]">
                  <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="approvedQuash" icon="el-icon-check"
                      v-hasPermi="['finance:paymentRequest:approved']" v-if="
                        scope.row.paymentStatus == 0 &&
                        scope.row.paymentReviewStatus == 0 &&
                        Number(scope.row.deleteStatus) === 0
                      ">核准（并生成付款单）</el-dropdown-item>
                    <el-dropdown-item command="rejectQuash" icon="el-icon-close"
                      v-hasPermi="['finance:paymentRequest:reject']" v-if="
                        scope.row.paymentStatus == 0 &&
                        scope.row.paymentReviewStatus == 0 &&
                        Number(scope.row.deleteStatus) === 0
                      ">驳回</el-dropdown-item>
                    <el-dropdown-item command="voucherQuash" icon="el-icon-finished"
                      v-hasPermi="['finance:paymentRequest:voucher']" v-if="
                        scope.row.paymentStatus == 0 &&
                        scope.row.paymentReviewStatus == 1 &&
                        Number(scope.row.deleteStatus) === 0
                      ">付款</el-dropdown-item>
                    <el-dropdown-item command="processQuash" icon="el-icon-document"
                      v-hasPermi="['product:PaymentRequestProcess:list']">详情</el-dropdown-item>
                    <el-dropdown-item command="requestQuash" icon="el-icon-s-operation">日志</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>

      <el-table-column label="采购订单号" align="center" prop="ordersNumber">
        <template slot-scope="scope">
          <span class="link-text" @click="openDialog(scope.row)">
            {{ scope.row.ordersNumber }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="采购计划" align="center" prop="planNumber" />
      <el-table-column label="供应商名称" align="center" prop="vendorName" />
      <el-table-column label="采购员" align="center" prop="buyer" />
      <el-table-column label="应付金额" align="center" prop="amountDue">
        <template v-slot="scope">
          {{ scope.row.amountDue.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="deleteStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tb_delete_status" :value="scope.row.deleteStatus" />
        </template>
      </el-table-column>
      <el-table-column label="撤回备注" align="center" prop="revokeRemark">
        <template slot-scope="scope">
          <span>{{ scope.row.revokeRemark || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="货币" align="center" prop="monetaryName" />
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 详情页 -->
    <el-dialog :title="titleView" :visible.sync="openView" width="800px" append-to-body>
      <el-form :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商:" prop="name">
              {{ form.name }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购单号:" prop="ordersNumber">
              {{ form.ordersNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款金额:" prop="requestAmount">
              {{ form.requestAmount }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="货币:" prop="monetaryName">
              {{ form.monetaryName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请人:" prop="applicant">
              {{ form.applicant }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请日期:" prop="requestAmount">
              {{ parseTime(form.requestAmount, "{y}-{m}-{d}") }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="付款状态:" prop="advanceStatus">
              <template v-if="form.advanceStatus == 0">未付款</template>
              <template v-else>已生成付款单</template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:" prop="requestRemark">
              {{ form.requestRemark }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitView">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 审核日志记录 -->
    <el-dialog :visible.sync="openLog" width="1400px" append-to-body :close-on-click-modal="false">
      <el-table v-loading="loading" :data="PaymentRequestLogList" height="500px">
        <el-table-column label="采购订单号" align="center" prop="ordersNumber" />
        <el-table-column label="审核状态" align="center" prop="logStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.process_status" :value="scope.row.logStatus" />
          </template>
        </el-table-column>
        <el-table-column label="审核人" align="center" prop="logApplicant" />
        <el-table-column label="审核时间" align="center" prop="logTime" />
        <el-table-column label="审核备注" align="center" prop="logRemark" />
        <el-table-column label="申请人" align="center" prop="applicant" />
        <el-table-column label="申请时间" align="center" prop="applicationTime" />
      </el-table>

      <pagination v-show="logTotals > 0" :total="logTotals" :page.sync="logParam.pageNum"
        :limit.sync="logParam.pageSize" @pagination="getPaymentRequestLogList" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRequestLog">关闭</el-button>
      </div>
    </el-dialog>

    <el-drawer title="详情" :visible.sync="drawer">
      <div class="drawerValueUserImg">
        <image-preview :src="this.drawerValue.avatar" :width="50" :height="50" />
      </div>
      <div class="drawerValueSingleHanded">
        <h3>{{ this.drawerValue.applicant }}提交的申请记录</h3>
      </div>
      <div class="drawerValuePlanStatus">
        <dict-tag :options="dict.type.payment_review_status" :value="this.drawerValue.paymentReviewStatus" />
      </div>
      <el-descriptions class="margin-top" :column="2" direction="vertical">
        <el-descriptions-item label="采购单号" :span="2"><span style="color: black">{{
          this.drawerValue.ordersNumber
            }}</span></el-descriptions-item>
        <el-descriptions-item label="申请人"><span style="color: black">{{
          this.drawerValue.applicant
            }}</span></el-descriptions-item>
        <el-descriptions-item label="申请类型">
          <span style="color: black">
            <dict-tag :options="dict.type.request_payment_type" :value="this.drawerValue.paymentType" />
          </span></el-descriptions-item>
        <el-descriptions-item label="应付金额">
          <span style="color: black">{{
            this.drawerValue.amountDue
          }}</span></el-descriptions-item>
        <el-descriptions-item label="申请金额">
          <span style="color: black; font-weight: bold">
            {{
              this.drawerValue.payableAmount
                ? this.drawerValue.payableAmount +
                " " +
                this.drawerValue.monetaryName
                : this.drawerValue.prepaymentAmount +
                " " +
                this.drawerValue.monetaryName
            }}
          </span>
        </el-descriptions-item>
      </el-descriptions>
      <hr />
      <div>
        <div>
          <image-preview :src="this.drawerValue.avatar" :width="50" :height="50" />
          <div class="sponsor">发起人</div>
          <div class="sponsor-name">{{ this.drawerValue.applicant }}</div>
          <div class="sponsor-time">
            {{ parseTime(this.drawerValue.applicationTime, "{y}-{m}-{d}") }}
            {{ parseTime(this.drawerValue.applicationTime, "{h}:{i}") }}
          </div>
        </div>
        <div></div>
      </div>
      <div class="_scroll-container">
        <div v-for="(item, index) in PaymentRequestProcessData" :key="index"
          :class="index === 0 ? '' : 'postUserDept-css'">
          <image-preview :src="item.avatar" :width="50" :height="50" />
          <div class="sponsor">审批人</div>
          <div class="sponsor-name">
            {{ item.nickName }}
            <span v-if="item" v-show="item.processStatus == 0 || item.processStatus == null">
              (审核中)
            </span>
            <span v-if="item" v-show="item.processStatus == 1">
              (同意)&nbsp;&nbsp;{{ item.processTime }}
            </span>
            <span v-if="item" v-show="item.processStatus == 2">
              (拒绝) &nbsp;&nbsp;{{ item.processTime }}
            </span>
          </div>
          <div class="sponsor-time">
            {{ item.deptName }}
          </div>
          <div class="postUserDept-postName">
            {{ item.roleName }}
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 弹窗 -->
    <el-dialog title="提示" :visible.sync="rejectDialogVisible" width="350px" @close="resetRejectForm">
      <p>您确定将所选记录驳回吗？</p>

      <!-- 输入框：填写驳回原因 -->
      <el-form :model="rejectForm" :rules="rules" ref="rejectFormRef">
        <el-form-item label="驳回原因" prop="processRemark">
          <el-input type="textarea" placeholder="请输入驳回原因" v-model="rejectForm.processRemark" rows="3" />
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="submitReject" :loading="loading">
          确定
        </el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改采购订单对话框 -->
    <el-dialog :ordersTitle="title" :visible.sync="ordersOpen" width="80%" append-to-body :close-on-click-modal="false">
      <el-form ref="ordersForm" :model="ordersForm" label-width="80px">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="基础信息" name="first">
            <el-row>
              <el-col :span="6">
                <el-form-item label="采购单号:" prop="ordersNumber">
                  <el-input v-model="ordersForm.ordersNumber" placeholder="请输入计划单号" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="快递单号" prop="expressNumber">
                  <el-input v-model="ordersForm.expressNumber" placeholder="请输入快递单号" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="总件数" prop="total">
                  <el-input v-model="ordersForm.total" placeholder="请输入总件数" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="应付金额" prop="amountDue">
                  <el-input v-model="ordersForm.amountDue" placeholder="请输入应付金额" :disabled="true" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="6">
                <el-form-item label="计划单号:" prop="planNumber">
                  <el-input v-model="ordersForm.planNumber" placeholder="请输入计划单号" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购日期" prop="planDate">
                  <el-date-picker clearable v-model="form.planDate" type="date" value-format="yyyy-MM-dd"
                    placeholder="请选择采购日期" style="width: 210px" :default-value="new Date().toISOString().split('T')[0]"
                    :disabled="true">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="6">
                <el-form-item label="供应商" prop="vendorId">
                  <treeselect v-model="form.vendorId" :options="vendorOptions" :show-count="true" placeholder="请输入供应商"
                    @input="autoFillModelVendorId" :disabled="true" />
                </el-form-item>
              </el-col> -->
              <el-col :span="6">
                <el-form-item label="采购公司" prop="companyId">
                  <treeselect v-model="ordersForm.companyId" :options="companyOptions" :show-count="true"
                    placeholder="请输入采购公司" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="批次号" prop="purchaseBatchNumber">
                  <el-input v-model="ordersForm.purchaseBatchNumber" :disabled="true" placeholder="批次号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="采购部门:" prop="deptName">
                  <el-input v-model="ordersForm.deptName" placeholder="请输入采购部门" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购人员" prop="userName">
                  <el-input v-model="ordersForm.userName" placeholder="请输入采购人员" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="预入仓库" prop="warehouseId">
                  <treeselect v-model="ordersForm.warehouseId" :options="warehouseOptions" :show-count="true"
                    placeholder="请输入预入仓库" :disabled="true" />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="6">
                <el-form-item label="货币单位" prop="monetaryId">
                  <treeselect v-model="form.monetaryId" :options="monetaryOptions" :show-count="true"
                    placeholder="请输入货币单位" :disabled="true" />
                </el-form-item>
              </el-col> -->
            </el-row>
            <el-row>
              <!-- <el-col :span="6">
                <el-form-item label="汇率" prop="currency">
                  <el-input v-model="form.currency" placeholder="请输入汇率" :disabled="true" />
                </el-form-item>
              </el-col> -->
              <!-- <el-col :span="6">
                <el-form-item label="运费" prop="freight">
                  <el-input v-model="form.freight" placeholder="请输入运费" :disabled="true" />
                </el-form-item>
              </el-col> -->

            </el-row>
            <!-- 备注展示框 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注展示:" prop="remark">
                  <el-input v-model="ordersForm.remark" type="textarea" :rows="4" :disabled="true"
                    class="remark-display-box"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider content-position="center">采购订单商品信息</el-divider>
            <el-row :gutter="10" class="mb8"> </el-row>
            <el-table :data="ordersProductList" :row-class-name="rowOrdersProductIndex"
              @selection-change="handleOrdersProductSelectionChange" ref="ordersProduct" height="210px">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="序号" align="center" prop="index" min-width="50" />
              <el-table-column label="图片" prop="imagePath" align="center" min-width="200">
                <template slot-scope="scope">
                  <div class="image-container">
                    <image-preview v-for="(image, index) in scope.row.imagePath" :key="index" :src="image" :width="50"
                      :height="50" class="image-item" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="SKU " prop="sku" min-width="150">
                <template slot-scope="scope">
                  <el-tooltip :content="scope.row.sku || '-'" placement="top" :disabled="!scope.row.sku">
                    <span>{{ scope.row.sku || '-' }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column label="产品名称" prop="productName" min-width="150">
                <template slot-scope="scope">
                  <el-tooltip :content="scope.row.productName || '-'" placement="top"
                    :disabled="!scope.row.productName">
                    <span>{{ scope.row.productName || '-' }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column label="数量" prop="transferableNumber" min-width="150">
                <template slot-scope="scope">
                  <TooltipCell :value="scope.row.transferableNumber" />
                </template>
              </el-table-column>
              <el-table-column label="产品价格" prop="productPrice" min-width="150">
                <template slot-scope="scope">
                  <TooltipCell :value="scope.row.productPrice" />
                </template>
              </el-table-column>
              <!-- 税率 -->
              <el-table-column label="税率" prop="productRate" :min-width="100">
                <template slot-scope="scope">
                  <el-tooltip class="item" effect="dark"
                    :content="scope.row.productRate != null ? scope.row.productRate.toString() + '%' : '-'"
                    placement="top">
                    <span>{{ scope.row.productRate != null ? scope.row.productRate + '%' : '-' }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <!-- 总成本 -->
              <el-table-column label="总成本" prop="totalCost" :min-width="120">
                <template slot-scope="scope">
                  <el-tooltip class="item" effect="dark"
                    :content="scope.row.totalCost != null ? scope.row.totalCost.toString() : '-'" placement="top">
                    <span>{{ scope.row.totalCost != null ? scope.row.totalCost : '-' }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <!-- 单品成本 -->
              <el-table-column label="单品成本" :min-width="120">
                <template slot-scope="scope">
                  <el-tooltip class="item" effect="dark" :content="scope.row.transferableNumber && scope.row.totalCost != null
                    ? (scope.row.totalCost / scope.row.transferableNumber).toFixed(2)
                    : '-'" placement="top">
                    <span>
                      {{ scope.row.transferableNumber && scope.row.totalCost != null
                        ? (scope.row.totalCost / scope.row.transferableNumber).toFixed(2)
                        : '-' }}
                    </span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column label="金额" prop="amount" min-width="150">
                <template slot-scope="scope">
                  <el-tooltip :content="scope.row.amount != null ? scope.row.amount.toString() : '-'" placement="top"
                    :disabled="scope.row.amount == null">
                    <span>{{ scope.row.amount != null ? scope.row.amount.toString() : '-' }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column label="供应商" prop="vendorId" min-width="270">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.vendorId" disabled placeholder="" filterable size="medium"
                    style="min-width: 250px;">
                    <el-option v-for="item in vendorOptions" :key="item.id" :label="item.label" :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="交付时间" prop="deliveryTime" min-width="230">
                <template slot-scope="scope">
                  <el-date-picker v-model="scope.row.deliveryTime" disabled type="datetime" placeholder=""
                    format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                </template>
              </el-table-column>

              <!-- 货币单位列 -->
              <el-table-column label="货币单位" prop="monetaryId" min-width="150">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.monetaryId" placeholder="" disabled
                    @change="handleCurrencyChangeRow(scope.row)">
                    <el-option v-for="item in monetaryOptions" :key="item.id" :label="item.label" :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>

              <!-- 新增每个产品的汇率输入 -->
              <el-table-column label="汇率" prop="currency" min-width="130">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.currency" disabled placeholder=""
                    @input="handleRateChangeRow(scope.row)" />
                </template>
              </el-table-column>
              <!-- 新增每个产品的运费输入 -->
              <el-table-column label="运费" prop="freight" min-width="130">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.freight" disabled placeholder="" />
                </template>
              </el-table-column>
              <el-table-column label="入库数量" prop="storageNumber" min-width="150">
                <template slot-scope="scope">
                  <el-tooltip :content="scope.row.storageNumber || '-'" placement="top"
                    :disabled="!scope.row.storageNumber">
                    <span>{{ scope.row.storageNumber || '-' }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="productRemark" min-width="150">
                <template slot-scope="scope">
                  <el-tooltip :content="scope.row.productRemark || '-'" placement="top"
                    :disabled="!scope.row.productRemark">
                    <span>{{ scope.row.productRemark || '-' }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <!-- 添加合计金额显示区域 -->
            <el-row style="margin-top: 10px;">
              <el-col :span="24">
                <div class="total-amount-box">
                  <span class="total-label">合计金额：</span>
                  <span class="total-value">{{ calculateTotalAmount }}</span>
                </div>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="合同备注" name="second">
            <el-row>
              <el-col :span="24">
                <editor v-model="form.contract" :min-height="192" ref="quillEditor" />
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPaymentRequest, //申请款列表
  rejectPaymentRequest, //驳回
  approvedPaymentRequest, //核准
  voucherPaymentRequest, //付款
} from "@/api/finance/paymentRequest";
import {
  getProcuredOrders,//采购订单详情
  selectPaymentRequestLogList,
  getPaymentRequestProcessList,
} from "@/api/orders/ProcuredOrders";
import {
  getSelectVendorTreeList,
  getSelectCompanyTreeList,
  getSelectPreWarehouseTreeList,
  getSelectMonetaryTreeList
} from "@/api/procured/plan";
import Treeselect from "@riophae/vue-treeselect";
import store from "@/store";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "PaymentRequest",
  dicts: [
    "request_payment_status", //付款状态
    "payment_review_status", //申请状态
    "request_payment_type", //付款类型
    "process_status", //日志审核状态
    "tb_delete_status"
  ],
  components: {
    Treeselect,
    TooltipCell: {
      name: 'TooltipCell',
      functional: true, // 采用函数式组件更轻量
      props: {
        value: {
          type: [String, Number],
          default: null
        }
      },
      render(h, ctx) {
        // 当 value 为 null/undefined/空值时显示 '-'，否则转成字符串
        const val = ctx.props.value != null && ctx.props.value !== '' ? String(ctx.props.value) : '-';
        return h(
          'el-tooltip',
          {
            props: {
              content: val,
              placement: 'top',
              disabled: !(ctx.props.value != null && ctx.props.value !== '')
            }
          },
          [h('span', val)]
        );
      }
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      idss: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 申请款表格数据
      paymentRequestList: [],
      // 存储每个子表的选中数据
      selectedItems: {},
      // 弹出层标题
      title: "",
      titleView: "",
      // 是否显示弹出层
      open: false,
      openView: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ordersNumber: null,
        paymentRequestCode: null,
        vendorId: null,
        paymentStatus: null,
        reviewerUserId: null,
        paymentReviewStatus: null,
        deleteStatus: '0'
      },
      // 表单参数
      form: {},
      // 表单校验
      // 供应商
      vendorOptions: [],
      //日志
      openLog: false,
      PaymentRequestLogList: [],
      // 查询参数
      logParam: {
        pageNum: 1,
        pageSize: 10,
      },
      logTotals: 0,
      isSubmitting: false,
      //当前用户id
      userId: store.getters.userId,
      drawer: false,
      drawerValue: {},
      PaymentRequestProcessData: [],
      PaymentRequestProcessLength: null,
      // 控制弹窗显示
      rejectDialogVisible: false,
      rejectForm: {
        processRemark: "", // 驳回原因
        paymentRequestIds: "",
      },
      rules: {
        processRemark: [
          { required: true, message: "请填写驳回原因", trigger: "blur" },
        ],
      },
      selectedRows: [],
      // 采购订单商品表格数据
      ordersProductList: [],
      // 表单参数
      ordersForm: {},
      ordersTitle: '',
      ordersOpen: false,
      activeName: "first",
      // 机构管理里
      companyOptions: [],
      // 仓库列表
      warehouseOptions: [],
      //货币单位
      monetaryOptions: [],
      selection: [],
      totalAmount: 0, //汇总金额
    };
  },
  computed: {
    calculateTotalAmount() {
      return this.ordersProductList.reduce((total, item) => {
        // 确保是数字，如果为空或非数字则视为0
        const amount = parseFloat(item.amount) || 0;
        return total + amount;
      }, 0).toFixed(2);
    },
  },
  created() {
    this.getPaymentRequestList();
    this.getVendor();
    this.getCompany();
    this.getPreWarehouse();
    this.getMonetary();
  },
  methods: {
    getList() {
      getPaymentRequestList();
    },
    /** 查询申请款列表 */
    getPaymentRequestList() {
      this.loading = true;
      this.queryParams.reviewerUserId = this.userId;
      const value = this.queryParams.statusFilter;
      if (value) {
        if (value.startsWith("pay-")) {
          this.queryParams.paymentStatus = value.replace("pay-", "");
          this.queryParams.paymentReviewStatus = null;
        } else if (value.startsWith("review-")) {
          this.queryParams.paymentReviewStatus = value.replace("review-", "");
          this.queryParams.paymentStatus = null;
        }
      } else {
        this.queryParams.paymentStatus = null;
        this.queryParams.paymentReviewStatus = null;
      }

      listPaymentRequest(this.queryParams).then((response) => {
        this.paymentRequestList = response.rows;
        this.paymentRequestList.forEach((row) => {
          if (row.paymentRequests && row.vendorName) {
            row.paymentRequests.forEach((paymentRequest) => {
              paymentRequest.vendorName = row.vendorName; // 将 vendorName 添加到子表每一项
              paymentRequest.monetaryName = row.monetaryName;
              paymentRequest.amountDue = row.amountDue;
              paymentRequest.deleteStatus = row.deleteStatus;
              paymentRequest.ordersNumber = row.ordersNumber;
            });
          }
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPaymentRequestList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection, key) {
      // 每个 key 保存对应 selection（key 就是父级订单号）
      this.$set(this.selectedItems, key, selection);

      // 合并所有被选中的子项
      const allSelected = Object.values(this.selectedItems).flat();

      // 提取 id 等数据
      this.ids = allSelected.map(item => item.paymentRequestId);
      this.idss = allSelected.map(item => item.advanceId);
      this.single = allSelected.length !== 1;
      this.multiple = !allSelected.length;
      this.selectedRows = allSelected;
      this.selection = allSelected;

      // 汇总金额
      this.totalAmount = allSelected.reduce((sum, item) => {
        const amount = item.payableAmount ?? item.prepaymentAmount ?? 0;
        return sum + Number(amount);
      }, 0);
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "finance/advance/export",
        {
          ...this.queryParams,
        },
        `advance_${new Date().getTime()}.xlsx`
      );
    },
    /** 查询供应商的下拉数据结果 */
    getVendor() {
      getSelectVendorTreeList().then((response) => {
        this.vendorOptions = response.data;
      });
    },

    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "voucherQuash":
          this.sumbitVoucher(row, true);
          break;
        case "approvedQuash":
          this.submitApproved(row, true);
          break;
        case "rejectQuash":
          this.handleReject(row, true);
          break;
        case "processQuash":
          this.borderTrigger(row);
          break;
        case "requestQuash":
          this.paymentRequestLog(row);
          break;
        default:
          break;
      }
    },
    /**详情确定按钮 */
    submitView() {
      this.openView = false;
    },
    //检查是否都是审核中
    checkStatus(title) {
      const hasNonReviewStatus = this.selectedRows.some(
        (row) => row.paymentReviewStatus !== "0"
      );
      if (hasNonReviewStatus) {
        this.$message.error(title + "，请选择【审核中】的数据");
        return false;
      }
      return true;
    },
    //检查是否同一供应商,检查是否都是已审核+未付款
    checkVoucher(title) {
      const hasSameVendor = this.selectedRows.every(
        (row) => row.vendorName === this.selectedRows[0]?.vendorName
      );
      if (!hasSameVendor) {
        this.$message.error(title + "，请选择相同供应商");
        return false;
      }

      const hasSameMonetaryName = this.selectedRows.every(
        (row) => row.monetaryName === this.selectedRows[0]?.monetaryName
      );
      if (!hasSameMonetaryName) {
        this.$message.error(title + "，请选择相同货币");
        return false;
      }

      // const hasNonReviewStatus = this.selectedRows.every(
      //   (row) => row.paymentReviewStatus == "1" && row.paymentStatus == "0"
      // );
      // if (!hasNonReviewStatus) {
      //   this.$message.error(title + "，请选择【已审核＋未付款】的数据");
      //   return false;
      // }
      return true;
    },
    /**付款按钮 */
    sumbitVoucher(selectRow, isBoolean) {
      if (!isBoolean) {
        if (!this.checkVoucher("付款")) {
          return;
        }
      }
      const paymentRequestIds = selectRow.paymentRequestId || this.ids;
      this.$modal
        .confirm("您确定付款所选数据吗？（付款将生成付款单）")
        .then(function () {
          return voucherPaymentRequest(paymentRequestIds);
        })
        .then(() => {
          this.handleQuery();
          this.resetData();
          this.$modal.msgSuccess("付款成功!");
        })
        .catch(() => { });
    },
    checkIsDelete() {
      if (!this.selection || this.selection.length === 0) {
        this.$message.warning("请先勾选订单");
        return false;
      }
      const validList = this.selection.every(item => Number(item.deleteStatus) === 0);
      if (!validList) {
        this.$message.warning("请选择订单状态为【正常】");
        return false;
      }
      return true;
    },
    /**核准按钮 */
    submitApproved(selectRow, isBoolean) {

      if (!this.checkIsDelete()) {
        return;
      }

      if (!isBoolean) {
        if (!this.checkStatus("批量核准（并生成付款单）")) {
          return;
        }
        if (!this.checkVoucher("批量核准（并生成付款单）")) {
          return;
        }
      }
      const paymentRequestIds = selectRow.paymentRequestId || this.ids;
      this.$modal
        .confirm("您确认所选数据将核准（并生成付款单）吗？")
        .then(() => {
          return approvedPaymentRequest(paymentRequestIds);
        })
        .then(() => {
          this.getPaymentRequestList();
          this.resetData();
          this.$modal.msgSuccess("核准（并生成付款单）成功!");
          this.totalAmount = 0;
        })
        .catch(() => { });
    },
    resetData() {
      this.selectedRows = [];
      this.selection = [];
      this.ids = [];
      this.idss = [];
      this.selectedItems = {};
    },
    //驳回
    handleReject(row, isBoolean) {
      if (!this.checkIsDelete()) {
        return;
      }

      if (!isBoolean) {
        if (!this.checkStatus("批量驳回")) {
          return;
        }
      }
      this.rejectDialogVisible = true;
      this.rejectForm.paymentRequestIds = row.paymentRequestId || this.ids;
    },
    //重置
    resetRejectForm() {
      this.rejectForm = {
        processRemark: "",
        paymentRequestIds: [],
      };
      // 使用 $nextTick 确保在 DOM 更新后再执行重置
      this.$nextTick(() => {
        // 重置表单校验状态
        this.$refs.rejectFormRef.clearValidate();
      });
    },
    // 提交驳回原因
    submitReject() {
      // 表单校验
      this.$refs.rejectFormRef.validate((valid) => {
        if (valid) {
          this.loading = true;
          // 模拟接口请求
          setTimeout(() => {
            rejectPaymentRequest(
              this.rejectForm.paymentRequestIds,
              this.rejectForm.processRemark
            ).then((response) => {
              this.loading = false;
              this.rejectDialogVisible = false;
              this.resetData();
              // 提示成功
              this.$message.success("申请已驳回！");
            });
          }, 300);
        }
      });
    },
    //查审核日志
    paymentRequestLog(row) {
      this.openLog = true;
      this.logParam.paymentRequestId = row.paymentRequestId;
      this.getPaymentRequestLogList();
    },
    //查询所有的申请记录
    getPaymentRequestLogList() {
      this.loading = true;
      selectPaymentRequestLogList(this.logParam).then((response) => {
        this.PaymentRequestLogList = response.rows;
        this.logTotals = response.rows.length;
        this.loading = false;
      });
    },
    //关闭日志
    cancelRequestLog() {
      this.openLog = false;
    },
    //审核详情
    borderTrigger(data) {
      this.drawer = true;
      console.info(data);
      this.drawerValue = data;
      getPaymentRequestProcessList(data.paymentRequestId).then((r) => {
        this.PaymentRequestProcessLength = r.data.length;
        this.PaymentRequestProcessData = r.data;
      });
    },
    openDialog(row) {
      const ordersId = row.ordersId
      getProcuredOrders(ordersId).then((response) => {
        this.ordersForm = response.data;
        this.ordersProductList = response.data.ordersProductList;
        this.ordersOpen = true;
        this.ordersTitle = "采购订单详情";
      });
    },
    // 取消按钮
    cancel() {
      this.ordersOpen = false;
    },
    /** 查询供应商的下拉数据结果 */
    getVendor() {
      getSelectVendorTreeList().then((response) => {
        this.vendorOptions = response.data;
      });
    },
    /** 查询机构管理下拉数据结果 */
    getCompany() {
      getSelectCompanyTreeList().then((response) => {
        this.companyOptions = response.data;
      });
    },

    /** 查询仓库 */
    getPreWarehouse() {
      getSelectPreWarehouseTreeList().then((response) => {
        this.warehouseOptions = response.data;
      });
    },

    /** 货币单位 */
    getMonetary() {
      getSelectMonetaryTreeList().then((response) => {
        this.monetaryOptions = response.data;
      });
    },
    autoFillModelVendorId(row) {
      if (row != null) {
        getVendor(row).then((response) => {
          this.form.contract = response.data.contract;
        });
        this.form.contract = null;
      }
    },
    /** 采购订单商品序号 */
    rowOrdersProductIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 复选框选中数据 */
    handleOrdersProductSelectionChange(selection) {
      this.checkedOrdersProduct = selection.map((item) => item.index);
    },
  },
};
</script>
<style scoped>
.drawerValueUserImg {
  display: block;
}

.drawerValueSingleHanded {
  display: block;
  margin-top: -65px;
  margin-left: 96px;
}

.drawerValuePlanStatus {
  display: block;
  margin-top: -13px;
  margin-left: 98px;
}

.el-descriptions--mini:not(.is-bordered) .el-descriptions-item__cell {
  padding-bottom: 9px;
  font-size: 13px;
}

.margin-top {
  display: block;
  margin-top: 16px;
  margin-left: 20px;
}

.margin-top1 {
  display: block;
  margin-top: -47px;
  margin-left: 89px;
}

hr {
  border-color: #0000;
  height: 7px;
  background-color: #f3f3f3;
}

.el-descriptions-item__label.has-colon::after {
  content: ":";
  position: relative;
  top: -0.5px;
  display: none;
}

.sponsor {
  font-size: 14px;
  display: block;
  margin-top: -41px;
  margin-left: 96px;
}

.sponsor-name {
  font-size: 12px;
  display: block;
  margin-top: 4px;
  margin-left: 96px;
  color: #6f7174;
}

.sponsor-time {
  font-size: 12px;
  display: block;
  margin-top: -34px;
  margin-left: 439px;
  color: #6f7174;
}

.postUserDept-css {
  display: block;
  margin-top: 30px;
  height: auto;
}

.postUserDept-postName {
  font-size: 12px;
  display: block;
  margin-top: 3px;
  margin-left: 439px;
  color: #6f7174;
}

.block {
  display: block;
  margin-left: 19px;
  margin-top: 55px;
}

.processRemark-input {
  width: 70%;
  /* 占满可用宽度 */
  margin-bottom: 20px;
  /* 与按钮组的间距 */
}

.button-group {
  display: flex;
  float: right;
  transform: translateX(-30%);
  /* 修正因right的偏移 */
  gap: 50px;
  /* 按钮之间的间距 */
}

._scroll-container {
  margin-top: 45px;
  max-height: 450px;
  /* 设置最大高度 */
  overflow-y: auto;
  /* 垂直滚动 */
  border: 2px solid #ccc;
  /* 边框可选 */
}

.link-text {
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}
</style>
